#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

// 引入我们的解析器
const { parseDBCContent } = require('./dbc-parser.js');

// 所有DBC文件列表
const allDbcFiles = [
    'acura_ilx_2016_nidec.dbc',
    'bmw_e9x_e8x.dbc',
    'cadillac_ct6_chassis.dbc',
    'cadillac_ct6_object.dbc',
    'cadillac_ct6_powertrain.dbc',
    'chrysler_cusw.dbc',
    'chrysler_pacifica_2017_hybrid_private_fusion.dbc',
    'comma_body.dbc',
    'ESR.dbc',
    'fca_giorgio.dbc',
    'FORD_CADS.dbc',
    'FORD_CADS_64.dbc',
    'ford_cgea1_2_bodycan_2011.dbc',
    'ford_cgea1_2_ptcan_2011.dbc',
    'ford_fusion_2018_adas.dbc',
    'ford_fusion_2018_pt.dbc',
    'ford_lincoln_base_pt.dbc',
    'gm_global_a_chassis.dbc',
    'gm_global_a_high_voltage_management.dbc',
    'gm_global_a_lowspeed.dbc',
    'gm_global_a_lowspeed_1818125.dbc',
    'gm_global_a_object.dbc',
    'gm_global_a_powertrain_expansion.dbc',
    'gwm_haval_h6_phev_2024.dbc',
    'hongqi_hs5.dbc',
    'hyundai_2015_ccan.dbc',
    'hyundai_2015_mcan.dbc',
    'hyundai_i30_2014.dbc',
    'hyundai_kia_generic.dbc',
    'hyundai_santafe_2007.dbc',
    'luxgen_s5_2015.dbc',
    'mazda_2017.dbc',
    'mazda_3_2019.dbc',
    'mazda_radar.dbc',
    'mazda_rx8.dbc',
    'mercedes_benz_e350_2010.dbc',
    'nissan_xterra_2011.dbc',
    'opel_omega_2001.dbc',
    'rivian_park_assist_can.dbc',
    'rivian_primary_actuator.dbc',
    'tesla_can.dbc',
    'tesla_model3_party.dbc',
    'tesla_model3_vehicle.dbc',
    'tesla_powertrain.dbc',
    'toyota_2017_ref_pt.dbc',
    'toyota_adas.dbc',
    'toyota_iQ_2009_can.dbc',
    'toyota_prius_2010_pt.dbc',
    'toyota_radar_dsu_tssp.dbc',
    'toyota_tss2_adas.dbc',
    'volvo_v40_2017_pt.dbc',
    'volvo_v60_2015_pt.dbc',
    'vw_meb.dbc',
    'vw_mqb.dbc',
    'vw_mqbevo.dbc',
    'vw_pq.dbc'
];

function testFile(filename) {
    const filePath = path.join(__dirname, '..', 'opendbc', 'opendbc', 'dbc', filename);
    
    try {
        if (!fs.existsSync(filePath)) {
            return {
                filename,
                status: 'file_not_found',
                error: `文件不存在: ${filePath}`
            };
        }

        const content = fs.readFileSync(filePath, 'utf8');
        const startTime = Date.now();
        
        const database = parseDBCContent(content, filename);
        
        const endTime = Date.now();
        const parseTime = endTime - startTime;
        
        return {
            filename,
            status: 'success',
            size: `${(content.length / 1024).toFixed(1)}KB`,
            parseTime: `${parseTime}ms`,
            frames: database.frames.length,
            signals: database.frames.reduce((sum, frame) => sum + frame.signals.length, 0),
            warnings: database.warnings.length,
            hasFrames: database.frames.length > 0
        };
        
    } catch (error) {
        return {
            filename,
            status: 'failure',
            error: error.message,
            errorType: categorizeError(error.message)
        };
    }
}

function categorizeError(errorMessage) {
    if (errorMessage.includes('VAL_TABLE_')) return 'VAL_TABLE_语法错误';
    if (errorMessage.includes('意外的令牌')) return '语法解析错误';
    if (errorMessage.includes('期望')) return '语法期望错误';
    if (errorMessage.includes('重复')) return '重复定义错误';
    if (errorMessage.includes('m0') || errorMessage.includes('m1') || errorMessage.includes('多路复用')) return '多路复用错误';
    return '其他错误';
}

function runFullCompatibilityTest() {
    console.log('🚀 开始全面兼容性测试...\n');
    
    const results = [];
    let successCount = 0;
    let failureCount = 0;
    let zeroFrameCount = 0;
    
    process.stdout.write('进度: [');
    for (let i = 0; i < allDbcFiles.length; i++) {
        const filename = allDbcFiles[i];
        const result = testFile(filename);
        results.push(result);
        
        if (result.status === 'success') {
            successCount++;
            if (result.frames === 0) {
                zeroFrameCount++;
                process.stdout.write('0');
            } else {
                process.stdout.write('✓');
            }
        } else {
            failureCount++;
            process.stdout.write('✗');
        }
    }
    console.log(']');
    
    console.log('\n📊 测试总结:');
    console.log(`   总计: ${allDbcFiles.length} 个文件`);
    console.log(`   成功: ${successCount} 个文件`);
    console.log(`   失败: ${failureCount} 个文件`);
    console.log(`   成功但0帧: ${zeroFrameCount} 个文件`);
    console.log(`   成功率: ${Math.round((successCount / allDbcFiles.length) * 100)}%`);
    console.log(`   有效解析率: ${Math.round(((successCount - zeroFrameCount) / allDbcFiles.length) * 100)}%`);
    
    // 按错误类型分组
    const errorTypes = {};
    const zeroFrameFiles = [];
    
    results.forEach(r => {
        if (r.status === 'failure') {
            const type = r.errorType || '其他错误';
            errorTypes[type] = (errorTypes[type] || []).concat(r.filename);
        } else if (r.status === 'success' && r.frames === 0) {
            zeroFrameFiles.push(r.filename);
        }
    });
    
    if (Object.keys(errorTypes).length > 0) {
        console.log('\n❌ 失败文件按错误类型分组:');
        Object.entries(errorTypes).forEach(([type, files]) => {
            console.log(`   ${type} (${files.length} 个):`);
            files.forEach(f => console.log(`     - ${f}`));
        });
    }
    
    if (zeroFrameFiles.length > 0) {
        console.log('\n⚠️  成功但0帧的文件:');
        zeroFrameFiles.forEach(f => console.log(`   - ${f}`));
    }
    
    // 显示最佳表现的文件
    const goodFiles = results.filter(r => r.status === 'success' && r.frames > 0);
    if (goodFiles.length > 0) {
        console.log('\n✅ 成功解析的文件 (前10个):');
        goodFiles.slice(0, 10).forEach(r => {
            console.log(`   ${r.filename}: ${r.frames}帧, ${r.signals}信号, ${r.warnings}警告`);
        });
    }
    
    return results;
}

// 运行测试
if (require.main === module) {
    runFullCompatibilityTest();
}

module.exports = { runFullCompatibilityTest, testFile }; 